package com.frejoys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.dto.admin.StoreSaleListAndPageDto;
import com.frejoys.common.dto.store.StoreSaleListDto;
import com.frejoys.common.enums.EFileSize;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.util.AppConfigUtil;
import com.frejoys.common.util.TimeUtil;
import com.frejoys.common.vo.admin.StoreSaleListVo;
import com.frejoys.common.vo.store.StoreSaleVo;
import com.frejoys.dao.entity.*;
import com.frejoys.dao.mapper.*;
import com.frejoys.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class StoreSaleServiceImpl  extends ServiceImpl<StoreSaleMapper, StoreSale> implements StoreSaleService {

    private final StoreUserService storeUserService;

    private final OrderService orderService;

    private final OrderMapper orderMapper;

    private final StoreService storeService;

    private final StoreMapper storeMapper;

    private final StoreActivityService storeActivityService;

    private final StoreActivityMapper storeActivityMapper;

    private final ActivityService activityService;

    private final UserMapper userMapper;



    @Override
    public List<StoreSaleVo> getSaleList(StoreSaleListDto dto,Long userId) {

        // 用户没有店铺,或者查询的店铺不属于他,返空
        List<Integer> storeIdByUserId = storeUserService.getStoreIdByUserId(userId);
        if (CollectionUtils.isEmpty(storeIdByUserId)) {
            return Collections.emptyList();
        }
        if (dto.getStoreId() != null && !storeIdByUserId.contains(dto.getStoreId())) {
            return Collections.emptyList();
        }

        LambdaQueryWrapper<StoreSale> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dto.getStoreId()!=null,StoreSale::getStoreId,dto.getStoreId());
        queryWrapper.in(StoreSale::getStoreId,storeIdByUserId);
        if (dto.getYmd()!=null && dto.getYmd() != 0) {
            queryWrapper.eq(StoreSale::getYmd,dto.getYmd());
        } else if (dto.getYm()!=null && dto.getYm() != 0) {
            queryWrapper.eq(StoreSale::getYm,dto.getYm());
        }else if (dto.getY()!=null && dto.getY() != 0) {
            queryWrapper.eq(StoreSale::getY,dto.getY());
        }

        Page<StoreSale> page = new Page<>(dto.getPage(),dto.getSize());
        page.setSearchCount(false);

        // 分页查询销售记录
        List<StoreSale> records = baseMapper.selectPage(page, queryWrapper).getRecords();

        if (CollectionUtils.isEmpty(records)) {
            return Collections.emptyList();
        }

        List<StoreSaleVo> storeSaleVos = BeanUtil.copyToList(records, StoreSaleVo.class);
        List<Integer> storeIdList = storeSaleVos.stream().map(StoreSaleVo::getStoreId).toList();
        if (CollectionUtils.isEmpty(storeIdList)) {
            return Collections.emptyList();
        }

        // 查询每条销售记录参与的活动
        Map<Integer, Integer> activityStoreIdMap = new HashMap<>();
        List<Integer> activityIdList = storeSaleVos.stream().map(StoreSaleVo::getStoreActivityId).toList();
        if (!activityIdList.isEmpty()) {
            LambdaQueryWrapper<StoreActivity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.select(StoreActivity::getId,StoreActivity::getStoreId,StoreActivity::getType);
            lambdaQueryWrapper.in(StoreActivity::getId,activityIdList);
            List<StoreActivity> activities = storeActivityMapper.selectList(lambdaQueryWrapper);
            if (!activities.isEmpty()) {
                activityStoreIdMap = activities.stream().collect(Collectors.toMap(StoreActivity::getId, StoreActivity::getType));
            }
        }
        // 查询店铺名称及活动类型名称
        Map<Integer, String> storeNameMap = storeService.getIdNameMap(storeIdList);
        Map<Integer, String> activityNameMap =  activityService.getTypeNameMap();

        // 补充店铺名称,活动名称
        for (StoreSaleVo storeSaleVo : storeSaleVos) {
            storeSaleVo.setStoreName(storeNameMap.get(storeSaleVo.getStoreId()));
            Integer storeTmpId = activityStoreIdMap.get(storeSaleVo.getStoreActivityId());
            storeSaleVo.setStoreActivityName(activityNameMap.get(storeTmpId));
        }
        return storeSaleVos;
    }

    @Override
    public IPage<StoreSaleListVo> storeSaleList(StoreSaleListAndPageDto dto) {
        Page<StoreSale> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<StoreSale> wrapper = new LambdaQueryWrapper<>();
        if (dto.getStoreId() != null){
            wrapper.eq(StoreSale::getStoreId,dto.getStoreId());
        }
        if (StrUtil.isNotEmpty(dto.getStoreName())){
            List<Store> stores = storeMapper.getStoreNameById(dto.getStoreName());
            if (stores.isEmpty()){
                return new Page<>();
            }
            List<Integer> storeIds = stores.stream().map(Store::getId).toList();
            wrapper.in(StoreSale::getStoreId,storeIds);
        }
        if (StrUtil.isNotEmpty(dto.getStartTime()) && StrUtil.isNotEmpty(dto.getEndTime())){

            //只能赛选三个月的订单
            Long day = TimeUtil.diffDay(TimeUtil.unixTime(dto.getStartTime()), TimeUtil.unixTime(dto.getEndTime()));
            if (day > 90){
                throw new GeneralException(HttpStatus.filtrationSaleError);
            }

            Integer startTime = Integer.valueOf(TimeUtil.formatYMD(TimeUtil.unixTime(dto.getStartTime())));
            Integer endTime = Integer.valueOf((TimeUtil.formatYMD(TimeUtil.unixTime(dto.getEndTime()))));

            wrapper.ge(StoreSale::getYmd,startTime);
            wrapper.le(StoreSale::getYmd,endTime);
        }
        wrapper.orderByDesc(StoreSale::getCreateTime);
        Page<StoreSale> storeSalePage = baseMapper.selectPage(page, wrapper);
        IPage<StoreSaleListVo> storeSaleListVoIPage = storeSalePage.convert(storeSale -> BeanUtil.copyProperties(storeSale, StoreSaleListVo.class));
        List<StoreSaleListVo> list = storeSaleListVoIPage.getRecords();

        if (!list.isEmpty()){
            //代理人id
            List<Long> userIds = list.stream().map(StoreSaleListVo::getUserId).distinct().toList();
            //店铺id
            List<Integer> storeIds = list.stream().map(StoreSaleListVo::getStoreId).distinct().toList();
            //订单id
            List<Integer> orderIds = list.stream().map(StoreSaleListVo::getOrderId).toList();

            //查询代理人信息
            List<User> users = userMapper.getUserByIds(userIds);
            Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user));

            //查询店铺信息
            List<Store> stores = storeMapper.getStoreNameList(storeIds);
            Map<Integer, Store> storeMap = stores.stream().collect(Collectors.toMap(Store::getId, store -> store));

            //查询订单信息和下单用户信息
            LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
            orderWrapper.select(Order::getOrderSn,Order::getId,Order::getUserId)
                    .in(Order::getId,orderIds);
            List<Order> orders = orderMapper.selectList(orderWrapper);
            Map<Integer, Order> orderMap = orders.stream().collect(Collectors.toMap(Order::getId, order -> order));

            //下单用户信息
            List<Long> orderUserIds = orders.stream().map(Order::getUserId).toList();
            List<User> orderUser = userMapper.getUserByIds(orderUserIds);
            Map<Long, User> orderUserMap = orderUser.stream().collect(Collectors.toMap(User::getId, user -> user));

            for (StoreSaleListVo vo:list) {
                if (userMap.containsKey(vo.getUserId())){
                    vo.setNickname(userMap.get(vo.getUserId()).getNickname());
                    vo.setPhone(userMap.get(vo.getUserId()).getPhone());
                }
                if (storeMap.containsKey(vo.getStoreId())){
                    vo.setStoreName(storeMap.get(vo.getStoreId()).getName());
                    vo.setLogoUrl(AppConfigUtil.getUrlPrefix(storeMap.get(vo.getStoreId()).getLogo(), EFileSize.logo.getValue()));
                }
                if (orderMap.containsKey(vo.getOrderId())){
                    vo.setOrderSn(orderMap.get(vo.getOrderId()).getOrderSn());

                    if (orderUserMap.containsKey(orderMap.get(vo.getOrderId()).getUserId())){
                        User user = orderUserMap.get(orderMap.get(vo.getOrderId()).getUserId());
                        vo.setOrderUserNickname(user.getNickname());
                        vo.setOrderUserPhone(user.getPhone());
                        vo.setOrderUserId(user.getId());
                    }
                }
            }
        }
        return storeSaleListVoIPage;
    }

}
